package com.tech.koufu.ui.view;

import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.igexin.sdk.PushManager;
import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.StockInfo;
import com.tech.koufu.model.UserInfo;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.HttpUtils;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.BuyStocksActivity;
import com.tech.koufu.ui.activity.EntrustListActivity;
import com.tech.koufu.ui.activity.SellStocksListActivity;
import com.tech.koufu.ui.adapter.MainStocksAdapter;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import android.R.string;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 首页  用户登录后
 * @author luo
 *
 */
public class MainContentFragment extends Fragment implements OnClickListener{
	private static final String TAG = MainContentFragment.class.getName();
	private static final int MSG_USERINFO = 1;
	private static final int MSG_STOCK_LIST = 2;
	private static final int MSG_TIME_RUN = 3;
	private static final int MSG_KAIPAN = 4;
	private static final int REFRESH_FINISH = 5;
	private StringRequest stringRequest;
	private RequestQueue mQueue;
	private View view;
	private MyApplication myApp;
	private Message msg = new Message();
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private MainStocksAdapter mStocksAdapter;

	private UserInfo info = new UserInfo();
	private UserStocks ustocks;
	private StockInfo stocks;
	private StringBuilder stockparms = new StringBuilder();
	private Map<String,String> data;
	private TextView txt_main_mycount,txt_profit_rate,txt_total_money,
	txt_stock_price,txt_used_funds,txt_day_gains,txt_main_datetime;
	private TextView txt_main_timetitle; //开盘时间
	private ArrayList<UserStocks> list = new ArrayList<UserStocks>();
	private ArrayList<StockInfo> datas;
	private String timeReader,kaipanCount;
	MainActivity mainActivity ;
	private boolean isF5 = false;
	private View lvTop;
	
	public static MainContentFragment getInstance(String tag){
		Log.d(TAG, "~~~~~~~~MainContentFragment~~getInstance ~~~~~");
		MainContentFragment frg = new MainContentFragment();
		Bundle bundle = new Bundle();
		bundle.putString("tag", tag);
		frg.setArguments(bundle);
		return frg;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) { 
		if (view == null) {
			Log.d(TAG, "~~~~~~~~MainContentFragment~~onCreateView ~~~~~");
			view = inflater.inflate(R.layout.fragment_main_content, container,
					false);
			mainActivity = (MainActivity) getParentFragment().getActivity();
			myApp = (MyApplication)getActivity().getApplication();
			initView();
		} else {
			Log.d(TAG, "~~~~~~no~~~MainContentFragment~onCreateView ~~~~~~~~~~");
		}
		// 缓存的rootView需要判断是否已经被加过parent，
		// 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) view.getParent();
		if (parent != null) {
			parent.removeView(view);
		}
//		myApp = (MyApplication)getActivity().getApplication();
//		initView();
		 
//		getUserInfo();
//		initData();
//		DateTimeRun();
//		kaipanCount();

		return view;
	}
	
	 @Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		MobclickAgent.onPageStart("MainContent");
	}
	 
	 @Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		MobclickAgent.onPageEnd("MainContent"); 
	}
	 
	long stime ;
	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		stime = System.currentTimeMillis();
		getUserInfo();
		initData();
		DateTimeRun();
		kaipanCount();
	}

	public void initView() {
//		mainActivity.btnRefresh.setEnabled(true);
		mQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
		mPullToRefreshListView = (PullToRefreshListView)view.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
		registerForContextMenu(actualListView);

		lvTop = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.item_main_lv_top, null);
		actualListView.addHeaderView(lvTop,null,false);
		
		lvTop.findViewById(R.id.btn_buy_stock).setOnClickListener(this);
		lvTop.findViewById(R.id.btn_sell_stock).setOnClickListener(this);
		lvTop.findViewById(R.id.btn_etrust).setOnClickListener(this);

		txt_main_mycount = (TextView)view.findViewById(R.id.txt_main_mycount);
		txt_profit_rate = (TextView)lvTop.findViewById(R.id.txt_profit_rate);
		txt_total_money = (TextView)lvTop.findViewById(R.id.txt_total_money);
		txt_stock_price = (TextView)lvTop.findViewById(R.id.txt_stock_price);
		txt_used_funds = (TextView)lvTop.findViewById(R.id.txt_used_funds);
		txt_day_gains = (TextView)lvTop.findViewById(R.id.txt_day_gains);
		txt_main_datetime = (TextView)view.findViewById(R.id.txt_main_datetime);
		txt_main_timetitle = (TextView)view.findViewById(R.id.txt_main_timetitle);
	}
	private void initData(){
		datas = new ArrayList<StockInfo>();
		mStocksAdapter = new MainStocksAdapter(getActivity().getApplicationContext(),list);
		actualListView.setAdapter(mStocksAdapter);		
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	 refreshData(); 
		        }  
			}
		});  
	}
	public void refreshData(){ 
		if(isF5){
			return;
		}
		isF5 = true;
		stockparms = null;
		stockparms = new StringBuilder();
//		datas.clear();
//		list.clear();
		getUserInfo();  
	}
	private void getUserInfo(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String t = KouFuTools.readTimeInfo(new String());
				myApp = (MyApplication)getActivity().getApplication();
				data = new HashMap<String, String>();
				data.put("userid", myApp.getUserid());
				data.put("time", t);
				data.put("login", "1");
				String cookie = KouFuTools.descrypt(myApp.getUserid() + t );
				final String user = HttpUtils.postRequest(myApp.url+"Userinfo.dll", cookie ,data);
				//				Log.v("UserInfo=====>", user);
				if (user!=null && user.substring(0,1).equals("0")) {
					parseUserInfoJsonString(user);
					if(!(user.substring(user.lastIndexOf("|"), user.length())).equals("|") && 
							user.substring(user.lastIndexOf("|"), user.length()) !=null){

						parseStocksInfoJsonString(user);

					}
				}else{
					mHandler.post(new Runnable() {
						
						@Override
						public void run() { 
							if(user!=null)
								Toast.makeText(getActivity(),user.substring(2) , Toast.LENGTH_SHORT).show();
							else{
								Toast.makeText(getActivity(),"登录失败" , Toast.LENGTH_SHORT).show();
							}
							mPullToRefreshListView.onRefreshComplete();
						}
					});
					
				}
				


			}
		}).start();
	}

	private void parseUserInfoJsonString(String returnValue){
		if (returnValue!=null && returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(2, returnValue.lastIndexOf("|")).split(",");
			Log.v("MainContent=====>", returnValue.substring(2, returnValue.lastIndexOf("|")).toString());
			info.setTeamid(us[0].toString());
			info.setXzmc(us[1].toString());
			info.setZqlb(us[2].toString());
			String[] money = us[3].toString().split("\\|");
			info.setBeginMoney(money[0].toString());
			info.setCanUseMoney(money[1].toString());
			info.setAllMoney(us[4].toString());
			info.setRjyl(us[5].toString());
			info.setRyl(us[6].toString());
			info.setZyl(us[7].toString());
			info.setYyl(us[8].toString());
			info.setYll(us[9].toString());
			info.setCgl(us[10].toString());
			info.setZzl(us[11].toString());
			info.setPm(us[12].toString());
			info.setSj(us[13].toString());
			info.setCw(us[14].toString());
			info.setPj(us[15].toString());
			Log.v("MainContent=====>", info.toString());
			myApp.mUserInfo = info;
			myApp.setTeamid(us[0].toString());
			mHandler.sendEmptyMessage(MSG_USERINFO);

		}else {
			mHandler.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					Toast.makeText(getActivity(), "返回数据失败，请重新刷新页面", Toast.LENGTH_LONG).show();
				}
			});
			
		}
	}

	private void parseStocksInfoJsonString(String returnValue){
		if (returnValue.substring(0, 1).equals("0")) {
			String[] us = returnValue.trim().substring(returnValue.lastIndexOf("|")+1,returnValue.length()).split(";");
			Log.v("MainContent=====>", 
					returnValue.substring(returnValue.lastIndexOf("|"),returnValue.length()).toString());
			if(isF5){
				list.clear();
			}
			for(int i=0;i<us.length;i++){
				ustocks = new UserStocks();
				String[] a =  us[i].split(",");
				if(a.length > 0){
					ustocks.setStockId(a[0].toString().trim());
					ustocks.setStockName(a[1].toString().trim());
					ustocks.setStockHold(a[2].toString().trim());
					ustocks.setStockbj(a[4].toString().trim());
				}
				ustocks.setAllmoney(info.getAllMoney());
				ustocks.setTeamId(info.getTeamid());
				list.add(ustocks);
				stockparms.append(","+ustocks.getStockId());

			}
			myApp.mUserStocks = list;
			Log.v("stockParms=====>", stockparms.toString());
			Log.v("StockList==>", list.toString());
			if(stockparms.length()>1){
				getUserStocksInfo();
			}else{
				mHandler.obtainMessage(REFRESH_FINISH).sendToTarget();
			}
		}else{
			 mHandler.obtainMessage(REFRESH_FINISH).sendToTarget();
		}
	}

	private void getUserStocksInfo(){
		new Thread(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(stockparms!=null && !stockparms.equals("")){
					String stocks = HttpUtils.getRequest(myApp.url+"BinStock.dll?stock="
							+ stockparms.substring(1) +"&field=ZSP,JKP,CJE,ZG,ZD,ZX,BJ1,SJ1,CJL,SYL," +
							"BL1,BJ2,BL2,BJ3,BL3,SL1,SJ2,SL2,SJ3,SL3,BJ4,BL4,BJ5,BL5,SJ4,SL4,SJ5,SL5");
					Log.v("UserStocksInfo=====>", stocks);
					parseBinStockString(stocks);
				}
			}
		}).start();

	}

	private void parseBinStockString(String returnvalue){
		try {
			if(isF5){
				datas.clear();
			}
			String[] a = returnvalue.trim().split(";"); 
			for (int i = 0; i < a.length; i++) {
				String[] bs = a[i].split(",");
				stocks = new StockInfo();
				stocks.setCode(bs[0].toString().trim());
				stocks.setName(bs[1].toString().trim());
				stocks.setZsp(bs[2].toString().trim());
				stocks.setJkp(bs[3].toString().trim());
				stocks.setCje(bs[4].toString().trim());
				stocks.setZg(bs[5].toString().trim());
				stocks.setZd(bs[6].toString().trim());
				stocks.setZx(bs[7].toString().trim());			
				stocks.setBj1(bs[8].toString().trim());
				stocks.setSj1(bs[9].toString().trim());
				stocks.setCjl(bs[10].toString().trim());
				stocks.setSyl(bs[11].toString().trim());
				stocks.setBl1(bs[12].toString().trim());
				stocks.setBj2(bs[13].toString().trim());
				stocks.setBl2(bs[14].toString().trim());
				stocks.setBj3(bs[15].toString().trim());
				stocks.setBl3(bs[16].toString().trim());
				stocks.setSl1(bs[17].toString().trim());
				stocks.setSj2(bs[18].toString().trim());
				stocks.setSl2(bs[19].toString().trim());
				stocks.setSj3(bs[20].toString().trim());
				stocks.setSl3(bs[21].toString().trim());
				stocks.setBj4(bs[22].toString().trim());
				stocks.setBl5(bs[23].toString().trim());
				stocks.setBj5(bs[24].toString().trim());
				stocks.setBl5(bs[25].toString().trim());
				stocks.setSj4(bs[26].toString().trim());
				stocks.setSl4(bs[27].toString().trim());
				stocks.setSj5(bs[28].toString().trim());
				stocks.setSl5(bs[29].toString().trim());
				datas.add(stocks);
				list.get(i).setStockdqj(bs[7].toString().trim());
				//			ustocks.setStockdqj(bs[7].toString().trim());
				//			list.add(ustocks);
			} 
			myApp.mStockInfos = datas;
			if (datas.size() > 1 &&datas != null) {
				mHandler.sendEmptyMessage(MSG_STOCK_LIST);
			}
		} catch (Exception e) { 
			e.printStackTrace();
		}

	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_buy_stock:
			Intent intent = new Intent(getActivity(),ChooseStockFragment.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;
		case R.id.btn_sell_stock:
			intent = new Intent(getActivity(),SellStocksListActivity.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;
		case R.id.btn_etrust:
			intent = new Intent(getActivity(),EntrustListActivity.class); 
			intent.putExtra("userStock", list);
			startActivity(intent);
			break;

		default:
			break;
		}

	}

	private void loginPHP(){
		String url = Statics.URL_PHP + "login";

		stringRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				Log.v("PHPresponse", response);	
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		}){

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				Map<String, String> params = new HashMap<String, String>(); 
				//				params.put("userID", myApp.digitalid);
				//				params.put("userName", myApp.userName);
				params.put("userID", "3801857");
				params.put("userName", "test20150101");
				//				String baseID = Base64.encodeToString((myApp.digitalid + "|||" + myApp.userName).getBytes(),Base64.DEFAULT);
				//				Log.v("BASE64", myApp.digitalid + myApp.userName + "|" +baseID + ">>>" +myApp.getUserpwd());
				String baseID = Base64.encodeToString(("3801857|||test20150101").getBytes(),Base64.DEFAULT); 
				params.put("id", baseID);	
				params.put("password", "test20150101");
				Log.w(TAG, "clientid="+PushManager.getInstance().getClientid(getActivity()));
				params.put("clientID", PushManager.getInstance().getClientid(getActivity()));
				return params;
			}
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers;
					String rawCookies = responseHeaders.get("Set-Cookie"); 
					Log.v(TAG, "rawCookies="+rawCookies);
					myApp.phpsessid = rawCookies;
					//					if(rawCookies!=null){
					//						String[] rwcs = rawCookies.split(";");
					//						String phpsessid = rwcs[0];
					//						phpsessid = phpsessid.substring(phpsessid.lastIndexOf("="));
					//						Log.e("TTTt", "phpsessid="+phpsessid);
					//						myApp.phpsessid = phpsessid;
					//					} 
					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				//				return super.parseNetworkResponse(response);
			}
		};
		mQueue.add(stringRequest);
	}
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case MSG_USERINFO:
				if(info.getCw().equals("空仓")){
					txt_main_mycount.setText("0.00%仓");
				}else {
					txt_main_mycount.setText(info.getCw() + "仓");
				}

				Float ylzj = Float.valueOf(info.getAllMoney()) - Float.valueOf(info.beginMoney);
				if(ylzj > 0){
					txt_profit_rate.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_total_money.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_stock_price.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_used_funds.setTextColor(getResources().getColor(R.color.stockUpColor));
					txt_day_gains.setTextColor(getResources().getColor(R.color.stockUpColor));
				}else{
					txt_profit_rate.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_total_money.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_stock_price.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_used_funds.setTextColor(getResources().getColor(R.color.stockDownColor));
					txt_day_gains.setTextColor(getResources().getColor(R.color.stockDownColor));
				}
				DecimalFormat df =new DecimalFormat("00.00");
				String total_money = df.format(Float.valueOf(info.getAllMoney()));
				String canUse_money = df.format(Float.valueOf(info.getCanUseMoney()));
				String stock_price = df.format(Float.valueOf(total_money) - Float.valueOf(canUse_money));
				txt_profit_rate.setText(info.getYll() + "%");
				txt_total_money.setText(total_money);
				txt_stock_price.setText(stock_price);
				txt_used_funds.setText(canUse_money);
				txt_day_gains.setText(info.getYll() + "%");
				//				loginPHP();
				Log.d(TAG, "首页表格数据，共加载了"+(System.currentTimeMillis()-stime)/1000+"s的时间");
				break;
			case MSG_STOCK_LIST: 
				isF5 = false;
				mainActivity.cancleRefreshRotate();
				if(mStocksAdapter==null){
					mStocksAdapter = new MainStocksAdapter(getActivity().getApplicationContext(),list);
					actualListView.setAdapter(mStocksAdapter);		
				}else{
					mStocksAdapter.stockinfo = list;
				}
				mStocksAdapter.notifyDataSetChanged();
				mPullToRefreshListView.onRefreshComplete();
				Log.d(TAG, "首页列表数据，共加载了"+(System.currentTimeMillis()-stime)/1000+"s的时间");
				break;
			case MSG_TIME_RUN:
				txt_main_datetime.setText(timeReader);
			case MSG_KAIPAN:
				txt_main_timetitle.setText(kaipanCount);
			case REFRESH_FINISH:
				mPullToRefreshListView.onRefreshComplete();
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	private void DateTimeRun(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					while(true){
						String today = null;
						String thour;
						String tminute;
						Calendar calendar = Calendar.getInstance();
						int day = calendar.get(calendar.DAY_OF_WEEK);
						if (day == 2) {
							today = "星期一";
						}else if (day == 3) {
							today = "星期二";
						}else if (day == 4) {
							today = "星期三";
						}else if (day == 5) {
							today = "星期四";
						}else if (day == 6) {
							today = "星期五";
						}else if (day == 7) {
							today = "星期六";
						}else if (day == 1) {
							today = "星期日";
						}
						int hour = calendar.get(calendar.HOUR_OF_DAY);
						if(hour>=0 && hour < 10){
							thour = "0" + hour;
						}else{
							thour = "" + hour;
						}
						int minute = calendar.get(calendar.MINUTE);
						if(minute >= 0 && minute < 10){
							tminute = "0" + minute;
						}else{
							tminute = "" + minute;
						}
						timeReader = (calendar.get(Calendar.MONTH)+1) + "/" + calendar.get(calendar.DAY_OF_MONTH) + "  "
								+ thour + ":" + tminute + "  " + today;
						Thread.sleep(1000);
						mHandler.sendEmptyMessage(MSG_TIME_RUN);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}

	private void kaipanCount(){
		new Thread(new Runnable() {

			@Override
			public void run() {
				while(true){
					kaipanCount = KouFuTools.KaiPanTimeCount();
					mHandler.sendEmptyMessageDelayed(MSG_KAIPAN, 1000*60);
				}
			}
		}).start();
	}

}

